<script setup>
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import ComboBox from '../../components/ComboBox.vue';
import HotkeyManager from '../../components/HotkeyManager.vue';
import ModelManager from '../../components/ModelManager.vue';
import ThemeSettings from '../../components/ThemeSettings.vue';
import IndexingPanel from '../../components/IndexingPanel.vue';
import DiagnosticSettings from '../../components/DiagnosticSettings.vue';
import MenuManager from './MenuManager.vue';
import { setColorTheme, theme } from '../../assets/theme.js';
import { getAppSetting, setAppSetting, getHistoryConfigValue, setHistoryConfig, cleanupAllHistory } from '../../tauriApi';
import { useEditorStore } from '../../stores/editor';
import ConnectorDebugger from './ConnectorDebugger.vue'

const { t, locale } = useI18n();

const scope = ref('user'); // 'user' | 'workspace' (当前仅布局，均写入全局设置)
const section = ref('general'); // 'general' | 'appearance' | 'hotkeys' | 'models' | 'menus'
const search = ref('');

const colorMode = ref(theme.colorTheme);
const lang = ref(locale.value);

// editor settings state
const editorFontSize = ref(13);
const editorWordWrap = ref('off'); // 'off' | 'on' | 'bounded' | 'wordWrapColumn'
const editorMinimap = ref(false);
const editorWhitespace = ref('selection'); // 'none' | 'selection' | 'all'
const editorTabSize = ref(2);
const editorInsertSpaces = ref(true);
const editorReadOnly = ref(true);
const editorStore = useEditorStore();

// history settings state
const historyMaxFilesPerProject = ref(1000);
const historyMaxEntriesPerFile = ref(50);
const historyMaxAgeDays = ref(30);
const historyCleanupStatus = ref('');

const sections = computed(() => ([
   { id: 'general', label: t ? (t('app.settings_general') || 'General') : 'General' },
   { id: 'appearance', label: t ? (t('app.settings_appearance') || 'Appearance') : 'Appearance' },
   { id: 'editor', label: t ? (t('app.settings_editor') || 'Editor') : 'Editor' },
   { id: 'indexing', label: t ? (t('app.settings_indexing') || '索引管理') : '索引管理' },
   { id: 'diagnostics', label: '诊断设置' },
   { id: 'history', label: t ? (t('app.settings_history') || '历史记录') : '历史记录' },
   { id: 'hotkeys', label: t ? (t('app.settings_hotkeys') || 'Hotkeys') : 'Hotkeys' },
   { id: 'models', label: t ? (t('app.settings_models') || 'Models') : 'Models' },
   { id: 'menus', label: t ? (t('menus.title') || 'Menus') : 'Menus' },
   { id: 'connectors', label: 'Connectors' },
 ]));

const filteredSections = computed(() => {
  const q = String(search.value || '').trim().toLowerCase();
  if (!q) return sections.value;
  return sections.value.filter(s => String(s.label || '').toLowerCase().includes(q));
});

// Save history configuration
const saveHistoryConfig = async (key, value) => {
  try {
    await setHistoryConfig(key, value);
  } catch (e) {
    console.error('Failed to save history config:', e);
  }
};

// Cleanup all history
const performHistoryCleanup = async () => {
  try {
    historyCleanupStatus.value = 'running';
    const result = await cleanupAllHistory();
    historyCleanupStatus.value = 'success';
    setTimeout(() => {
      historyCleanupStatus.value = '';
    }, 3000);
  } catch (e) {
    historyCleanupStatus.value = 'error';
    setTimeout(() => {
      historyCleanupStatus.value = '';
    }, 3000);
  }
};

onMounted(async () => {
  try { await editorStore.initFromSettings(); } catch {}
  try { const v = await getAppSetting('colorTheme'); if (v) colorMode.value = v; } catch {}
  try { const v = await getAppSetting('language'); if (v) lang.value = v; } catch {}
  
  // load history settings
  try { const v = await getHistoryConfigValue('max_files_per_project'); historyMaxFilesPerProject.value = v; } catch {}
  try { const v = await getHistoryConfigValue('max_entries_per_file'); historyMaxEntriesPerFile.value = v; } catch {}
  try { const v = await getHistoryConfigValue('max_age_days'); historyMaxAgeDays.value = v; } catch {}
  
  // load editor settings
  editorFontSize.value = editorStore.fontSize;
  editorWordWrap.value = editorStore.wordWrap;
  editorMinimap.value = editorStore.minimapEnabled;
  editorWhitespace.value = editorStore.renderWhitespace;
  editorTabSize.value = editorStore.tabSize;
  editorInsertSpaces.value = editorStore.insertSpaces;
  editorReadOnly.value = editorStore.readOnly;
});

function onUpdateTheme(v){ colorMode.value = v; setColorTheme(v); setAppSetting('colorTheme', String(v||'system')); }
function onUpdateLang(v){ lang.value = v; locale.value = v; setAppSetting('language', String(v||'en')); }

function onEditorChange(key, value) {
  switch (key) {
    case 'fontSize': editorFontSize.value = value; editorStore.setFontSize(value); break;
    case 'wordWrap': editorWordWrap.value = value; editorStore.setWordWrap(value); break;
    case 'minimap': editorMinimap.value = !!value; editorStore.setMinimapEnabled(!!value); break;
    case 'renderWhitespace': editorWhitespace.value = value; editorStore.setRenderWhitespace(value); break;
    case 'tabSize': editorTabSize.value = value; editorStore.setTabSize(value); break;
    case 'insertSpaces': editorInsertSpaces.value = !!value; editorStore.setInsertSpaces(!!value); break;
    case 'readOnly': editorReadOnly.value = !!value; editorStore.setReadOnly(!!value); break;
  }
}
</script>

<template>
  <div class="settings-panel flex h-full min-h-0 flex-col">
    <!-- top search bar -->
    <div class="p-2 border-b border-panel-border">
      <input
        v-model="search"
        type="text"
        :placeholder="(t && (t('search.search') || 'Search')) + ' ' + ((t && (t('app.settings') || 'settings'))||'settings')"
        class="w-full rounded border border-panel-border px-2 py-1 text-sm bg-panel-bg text-panel-fg outline-none focus:border-accent thin-scrollbar"
      />
      <!-- scope tabs -->
      <div class="mt-2 flex items-center gap-1 text-xs">
        <button class="px-2 py-1 rounded border border-panel-border bg-panel-bg text-panel-fg hover:bg-subtle-bg transition-colors"
                :class="scope==='user' ? 'bg-subtle-bg' : ''"
                @click="scope='user'">{{ t ? (t('app.settings_user') || 'User') : 'User' }}</button>
        <button class="px-2 py-1 rounded border border-panel-border bg-panel-bg text-panel-fg hover:bg-subtle-bg transition-colors"
                :class="scope==='workspace' ? 'bg-subtle-bg' : ''"
                @click="scope='workspace'">{{ t ? (t('app.settings_workspace') || 'Workspace') : 'Workspace' }}</button>
      </div>
    </div>

    <!-- body: left nav + right content -->
    <div class="flex-1 min-h-0 flex">
      <!-- left menu -->
      <aside class="w-56 shrink-0 border-r border-panel-border overflow-auto p-2 text-sm thin-scrollbar scrollbar-compact scrollbar-track">
        <div v-for="s in filteredSections" :key="s.id"
             class="px-2 py-1 rounded cursor-pointer"
             :class="section===s.id ? 'bg-subtle-bg text-panel-fg' : 'text-muted-fg hover:bg-subtle-bg'"
             @click="section=s.id">
          {{ s.label }}
        </div>
        <div v-if="filteredSections.length===0" class="px-2 py-2 text-xs text-muted-fg">{{ t('app.no_matches') }}</div>
      </aside>

      <!-- right content -->
      <section class="flex-1 min-h-0 overflow-auto p-3 thin-scrollbar scrollbar-compact scrollbar-track">
        <div v-if="section==='general'" class="grid grid-cols-1 gap-3">
          <div class="flex items-center gap-3">
            <label class="w-28 text-xs text-muted-fg">{{ t('app.language_label') }}</label>
            <ComboBox :modelValue="lang" @update:modelValue="onUpdateLang"
                      :options="[{label:'English',value:'en'},{label:'简体中文',value:'zh'}]"
                      :searchable="false" size="sm" :minWidth="120" />
          </div>
        </div>

        <div v-else-if="section==='appearance'">
          <ThemeSettings />
        </div>

        <!-- Indexing settings -->
        <div v-else-if="section==='indexing'">
          <IndexingPanel />
        </div>

        <!-- Diagnostic settings -->
        <div v-else-if="section==='diagnostics'">
          <DiagnosticSettings />
        </div>

        <!-- Editor settings -->
        <div v-else-if="section==='editor'" class="grid grid-cols-1 gap-3">
          <div class="flex items-center gap-3">
            <label class="w-36 text-xs text-muted-fg">{{ t('app.editor_font_size') }}</label>
            <input type="number" min="10" max="24" step="1" class="w-24 rounded border border-panel-border px-2 py-1 text-sm bg-panel-bg text-panel-fg outline-none focus:border-accent"
                   :value="editorFontSize" @input="onEditorChange('fontSize', $event.target.valueAsNumber||13)" />
          </div>
          <div class="flex items-center gap-3">
            <label class="w-36 text-xs text-muted-fg">{{ t('app.editor_word_wrap') }}</label>
            <ComboBox :modelValue="editorWordWrap" @update:modelValue="(v)=> onEditorChange('wordWrap', v)"
                      :options="[{label:t('app.wrap_off'),value:'off'},{label:t('app.wrap_on'),value:'on'},{label:t('app.wrap_bounded'),value:'bounded'},{label:t('app.wrap_column'),value:'wordWrapColumn'}]"
                      :searchable="false" size="sm" :minWidth="140" />
          </div>
          <div class="flex items-center gap-3">
            <label class="w-36 text-xs text-muted-fg">{{ t('app.editor_minimap') }}</label>
            <input type="checkbox" :checked="editorMinimap" @change="onEditorChange('minimap', $event.target.checked)" />
          </div>
          <div class="flex items-center gap-3">
            <label class="w-36 text-xs text-muted-fg">{{ t('app.editor_render_whitespace') }}</label>
            <ComboBox :modelValue="editorWhitespace" @update:modelValue="(v)=> onEditorChange('renderWhitespace', v)"
                      :options="[{label:t('app.ws_none'),value:'none'},{label:t('app.ws_selection'),value:'selection'},{label:t('app.ws_all'),value:'all'}]"
                      :searchable="false" size="sm" :minWidth="140" />
          </div>
          <div class="flex items-center gap-3">
            <label class="w-36 text-xs text-muted-fg">{{ t('app.editor_tab_size') }}</label>
            <input type="number" min="2" max="8" step="1" class="w-24 rounded border border-panel-border px-2 py-1 text-sm bg-panel-bg text-panel-fg outline-none focus:border-accent"
                   :value="editorTabSize" @input="onEditorChange('tabSize', $event.target.valueAsNumber||2)" />
          </div>
          <div class="flex items-center gap-3">
            <label class="w-36 text-xs text-muted-fg">{{ t('app.editor_insert_spaces') }}</label>
            <input type="checkbox" :checked="editorInsertSpaces" @change="onEditorChange('insertSpaces', $event.target.checked)" />
          </div>
          <div class="flex items-center gap-3">
            <label class="w-36 text-xs text-muted-fg">{{ t('app.editor_read_only') }}</label>
            <input type="checkbox" :checked="editorReadOnly" @change="onEditorChange('readOnly', $event.target.checked)" />
          </div>
        </div>

        <!-- History settings -->
        <div v-else-if="section==='history'" class="grid grid-cols-1 gap-3">
          <div class="flex items-center gap-3">
            <label class="w-40 text-xs text-muted-fg">{{ t('app.history_max_files_per_project') }}</label>
            <input type="number" min="100" max="10000" step="100" 
                   class="w-24 rounded border border-panel-border px-2 py-1 text-sm bg-panel-bg text-panel-fg outline-none focus:border-accent"
                   :value="historyMaxFilesPerProject" 
                   @input="historyMaxFilesPerProject = $event.target.valueAsNumber || 1000; saveHistoryConfig('max_files_per_project', historyMaxFilesPerProject)" />
            <span class="text-xs text-muted-fg">{{ t('app.default') }}: 1000</span>
          </div>
          <div class="flex items-center gap-3">
            <label class="w-40 text-xs text-muted-fg">{{ t('app.history_max_entries_per_file') }}</label>
            <input type="number" min="10" max="200" step="10" 
                   class="w-24 rounded border border-panel-border px-2 py-1 text-sm bg-panel-bg text-panel-fg outline-none focus:border-accent"
                   :value="historyMaxEntriesPerFile" 
                   @input="historyMaxEntriesPerFile = $event.target.valueAsNumber || 50; saveHistoryConfig('max_entries_per_file', historyMaxEntriesPerFile)" />
            <span class="text-xs text-muted-fg">{{ t('app.default') }}: 50</span>
          </div>
          <div class="flex items-center gap-3">
            <label class="w-40 text-xs text-muted-fg">{{ t('app.history_max_age_days') }}</label>
            <input type="number" min="1" max="365" step="1" 
                   class="w-24 rounded border border-panel-border px-2 py-1 text-sm bg-panel-bg text-panel-fg outline-none focus:border-accent"
                   :value="historyMaxAgeDays" 
                   @input="historyMaxAgeDays = $event.target.valueAsNumber || 30; saveHistoryConfig('max_age_days', historyMaxAgeDays)" />
            <span class="text-xs text-muted-fg">{{ t('app.default') }}: 30{{ t('app.days') }}</span>
          </div>
          <div class="flex items-center gap-3 pt-2 border-t border-panel-border">
            <button @click="performHistoryCleanup" 
                    class="px-3 py-1.5 text-sm bg-danger-bg text-danger-fg hover:opacity-80 rounded border border-panel-border transition-colors"
                    :disabled="historyCleanupStatus === 'running'">
              {{ historyCleanupStatus === 'running' ? t('app.history_cleanup_running') : t('app.history_cleanup_button') }}
            </button>
            <span v-if="historyCleanupStatus && historyCleanupStatus !== 'running'" 
                   class="text-xs" 
                   :class="historyCleanupStatus === 'success' ? 'text-info-fg' : 'text-danger-fg'">
               {{ historyCleanupStatus === 'success' ? t('app.history_cleanup_success') : t('app.history_cleanup_error') }}
             </span>
          </div>
          <div class="text-xs text-muted-fg space-y-1">
            <p>• {{ t('app.history_cleanup_description_1') }}</p>
            <p>• {{ t('app.history_cleanup_description_2') }}</p>
            <p>• {{ t('app.history_cleanup_description_3') }}</p>
          </div>
        </div>

        <div v-else-if="section==='hotkeys'" class="grid grid-cols-1 gap-4">
          <HotkeyManager :defaults="{
            'toggle-ai': 'mod+j',
            'toggle-main': 'mod+b',
            'toggle-bottom': 'mod+\\',
            'open-settings': 'mod+,',
            'refresh-ai': 'f5',
            'focus-input': 'mod+/',
            // file operations
            'file:save': 'mod+s',
            'file:saveAs': 'mod+shift+s',
            'file:saveAll': 'mod+alt+s',
            'file:close': 'mod+w'
          }" />
        </div>

        <div v-else-if="section==='models'" class="grid grid-cols-1 gap-4">
          <ModelManager />
        </div>
        <div v-else-if="section==='menus'" class="grid grid-cols-1 gap-4">
          <MenuManager />
        </div>
        <div v-else-if="section==='connectors'" class="grid grid-cols-1 gap-4">
          <ConnectorDebugger />
        </div>
      </section>
    </div>
  </div>
</template>

<style scoped>
/* Settings-specific scrollbar fine-tuning */
.settings-panel .thin-scrollbar::-webkit-scrollbar { width: 6px; height: 6px; }
html:not(.dark) .settings-panel .thin-scrollbar::-webkit-scrollbar-thumb { background-color: rgba(100,116,139,.5); border-radius: 8px; border: 1.5px solid transparent; background-clip: padding-box; }
html:not(.dark) .settings-panel .thin-scrollbar::-webkit-scrollbar-thumb:hover { background-color: rgba(100,116,139,.7); }
html.dark .settings-panel .thin-scrollbar::-webkit-scrollbar-thumb { background-color: rgba(148,163,184,.4); border-radius: 8px; border: 1.5px solid transparent; background-clip: padding-box; }
html.dark .settings-panel .thin-scrollbar::-webkit-scrollbar-thumb:hover { background-color: rgba(148,163,184,.6); }

/* Apply optimized scrollbar to any overflow container inside settings panel */
.settings-panel :is(.overflow-auto, .overflow-y-auto, .overflow-x-auto) { scrollbar-width: thin; }
.settings-panel :is(.overflow-auto, .overflow-y-auto, .overflow-x-auto)::-webkit-scrollbar { width: 8px; height: 8px; }
html:not(.dark) .settings-panel :is(.overflow-auto, .overflow-y-auto, .overflow-x-auto)::-webkit-scrollbar-thumb { background-color: rgba(100,116,139,.55); border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
html:not(.dark) .settings-panel :is(.overflow-auto, .overflow-y-auto, .overflow-x-auto)::-webkit-scrollbar-thumb:hover { background-color: rgba(100,116,139,.75); }
html.dark .settings-panel :is(.overflow-auto, .overflow-y-auto, .overflow-x-auto)::-webkit-scrollbar-thumb { background-color: rgba(148,163,184,.45); border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
html.dark .settings-panel :is(.overflow-auto, .overflow-y-auto, .overflow-x-auto)::-webkit-scrollbar-thumb:hover { background-color: rgba(148,163,184,.65); }
</style>


